package com.fjec.common.convert;

import com.fjec.common.util.DateUtil;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.time.LocalDate;

public class StringToLocalDateConvert implements Converter<String, LocalDate> {

    private final static String miniPattern = "yyyyMMdd";
    private final static String shortPattern = "yyyy-MM-dd";

    @Override
    public LocalDate convert(String source) {
        if (StringUtils.hasText(source)) {
            try {
                return autoMatch(source);
            } catch (Exception e) {
                throw new IllegalArgumentException("this argument's format must be yyyy-MM-dd or yyyy-MM-dd HH:mm:ss");
            }
        }
        return null;
    }

    private LocalDate autoMatch(String strDate) {
        int len = strDate.length();
        LocalDate date = null;
        if (len == 8) {
            date = DateUtil.parseLd(strDate, miniPattern);
        } else if (len == 10) {
            date = DateUtil.parseLd(strDate, shortPattern);
        }
        return date;
    }
}
